/* eslint-disable no-undef */
import {Constant} from './Constant.js';
import {AppHttpRequestUtils} from './utils/AppHttpRequestUtils';
import {DragElements} from './bean/DragElements.js';
import {TableAttribute} from './bean/TableAttribute.js';
import {ElementUtils} from './utils/ElementUtils.js';
import {CommonUtils} from './utils/CommonUtils';
import ConfigInfo from './bean/ConfigInfo';
import ContactConfigInfo from './bean/ContactConfig.js';
import {ViewManager} from './view/ViewManager';
(function(PLUGIN_ID) {
  'use strict';
  const message = {
    'en': {
      query_area_title: 'Set Filter Condition for Data',
      mapping_result: 'Mapping Result',
      tab_setting: 'Settings',
      tab_graph: '&nbsp Graph &nbsp',
      show_graph: 'ShowGraph',
      save_status: 'Save Status',
      permission_error: 'Your Permission is Not Enough,Please Contact the Administrator!',
      pluginConfig_not_set_error: 'Your Plugin is Not Fully Configured，Please Complete the Configuration First!'
    },
    'zh': {
      query_area_title: '数据筛选条件设定',
      mapping_result: '映射结果',
      tab_setting: '设置',
      tab_graph: '图表',
      show_graph: '显示图表',
      save_status: '状态保存',
      permission_error: '您的权限不足，请联系管理员！',
      pluginConfig_not_set_error: '您的插件未配置完全，请先完成配置!'
    },
    'ja': {
      query_area_title: 'データ絞り込み条件設定',
      mapping_result: 'マッピング結果',
      tab_setting: 'セットアップ',
      tab_graph: 'チャート',
      show_graph: 'グラフを表示',
      save_status: '状態保存する',
      permission_error: 'あなたは閲覧権ありません、管理者に連絡してください!',
      pluginConfig_not_set_error: 'プラグインが正しく設定できていません!'
    }
  };
  const lang = kintone.getLoginUser().language;
  const i18n = (lang in message) ? message[lang] : message['zh'];
  let pluginConfig;
  const validateConfig = () => {
    pluginConfig = kintone.plugin.app.getConfig(PLUGIN_ID);
    return pluginConfig !== null;
  };

  if (!validateConfig()) {
    return;
  }
  const elementView = {};
  let viewManager;
  const contactElements = new DragElements();// resultListData
  const dragElementsList = [];// app fields list
  let needsReload = false;
  let customizationIndex = 0;
  const focusPosition = {};// focusPositon for query
  let originalData = {};// dataSourceMap
  let settingConfigInfo = new ConfigInfo();
  kintone.events.on('app.record.edit.show', (event)=>{
    if (checkPluginConfig()) {
      alert(i18n.pluginConfig_not_set_error);
      return event;
    }
    if (checkPermission(event.record)) {
      alert(i18n.permission_error);
      return event;
    }
    kintone.app.record.setFieldShown(`${pluginConfig[`${Constant.CONFIG_CONFIG_INFO_ID}`]}`, false);
    needsReload = true;
    event.record[`${pluginConfig[`${Constant.CONFIG_CONFIG_INFO_ID}`]}`].disabled = true;
    return event;
  });
  kintone.events.on(['app.record.index.edit.show', 'app.record.create.show'], (event)=>{
    if (checkPluginConfig()) {
      alert(i18n.pluginConfig_not_set_error);
      return event;
    }
    if (checkPermission(event.record)) {
      alert(i18n.permission_error);
      return event;
    }
    kintone.app.record.setFieldShown(`${pluginConfig[`${Constant.CONFIG_CONFIG_INFO_ID}`]}`, false);
    event.record[`${pluginConfig[`${Constant.CONFIG_CONFIG_INFO_ID}`]}`].disabled = true;
    return event;
  });
  kintone.events.on('app.record.detail.show', (event)=>{
    if (checkPluginConfig()) {
      alert(i18n.pluginConfig_not_set_error);
      return event;
    }
    if (needsReload) {
      needsReload = false;
      window.location.reload();
      return event;
    }
    const record = event.record;
    if (checkPermission(record)) {
      alert(i18n.permission_error);
      return event;
    }
    // hide unneeded record element
    kintone.app.record.setFieldShown(`${pluginConfig[`${Constant.CONFIG_FIRST_APP_ID}`]}`, false);
    kintone.app.record.setFieldShown(`${pluginConfig[`${Constant.CONFIG_SECOND_APP_ID}`]}`, false);
    kintone.app.record.setFieldShown(`${pluginConfig[`${Constant.CONFIG_CONFIG_INFO_ID}`]}`, false);
    // get configInfo for preview
    const configInfoString = record[`${pluginConfig[`${Constant.CONFIG_CONFIG_INFO_ID}`]}`].value;
    if (configInfoString !== '') {
      settingConfigInfo = JSON.parse(configInfoString);
    }
    viewManager = new ViewManager(`${pluginConfig[`${Constant.CONFIG_SPACE_ID}`]}`, i18n);
    viewManager.initTabView(elementView);
    viewManager.bindSaveStatusButtonListener(onSaveStatusButtonClick);
    $('#tab_view').tabs({
      activate: (e, ui) =>{
        const index = ui.newTab.index();
        if (index === 0 && dragElementsList.length > 1) {
          dragElementsList.forEach(dragElements =>{
            dragElements.showPoints();
          });
        } else if (dragElementsList.length > 1) {
          dragElementsList.forEach(dragElements =>{
            dragElements.hidePoints();
          });
        }
      }
    });
    // get app fields data
    const appRequests = [];
    let appId_1 = -1;
    let appId_2 = -1;
    if (`${pluginConfig[`${Constant.CONFIG_FIRST_APP_ID}`]}` !== ''
    && record[`${pluginConfig[`${Constant.CONFIG_FIRST_APP_ID}`]}`].value !== undefined
    && record[`${pluginConfig[`${Constant.CONFIG_FIRST_APP_ID}`]}`].value !== '') {
      appId_1 = record[`${pluginConfig[`${Constant.CONFIG_FIRST_APP_ID}`]}`].value;
    }
    if (`${pluginConfig[`${Constant.CONFIG_SECOND_APP_ID}`]}` !== ''
    && record[`${pluginConfig[`${Constant.CONFIG_SECOND_APP_ID}`]}`].value !== undefined
    && record[`${pluginConfig[`${Constant.CONFIG_SECOND_APP_ID}`]}`].value !== '') {
      appId_2 = record[`${pluginConfig[`${Constant.CONFIG_SECOND_APP_ID}`]}`].value;
    }
    if (appId_1 > 0) {
      appRequests.push(AppHttpRequestUtils.getAppElementInfo(appId_1));
    }
    if (appId_2 > 0 && appId_2 !== appId_1) {
      appRequests.push(AppHttpRequestUtils.getAppElementInfo(appId_2));
    }
    if (appRequests.length === 0) {
      return event;
    }
    if (settingConfigInfo.queryDatas !== undefined && Object.keys(settingConfigInfo.queryDatas).length !== appRequests.length) {
      settingConfigInfo = new ConfigInfo();
    }
    Promise.allSettled(appRequests).then(appElementInfos =>{
      let correctAppElementInfoLength = appElementInfos.length;
      elementView.settingsArea.innerText = '';
      appElementInfos.forEach((appElementInfo) =>{
        if (appElementInfo.status !== 'fulfilled') {
          correctAppElementInfoLength -= 1;
          return true;
        }
        const dragElements = appElementInfo.value.generateTableElements();
        // add custom table element
        const customElement = initCustomElement(dragElements.appId, dragElements.appName);
        dragElements.addElement(customElement);

        dragElementsList.push(dragElements);
        originalData = Object.assign(originalData, dragElements.elements);
        // init datasource_list
        const elementsListView = ElementUtils.generateElementsListView();
        const recordList = document.createElement('div');
        recordList.style.display = 'inline-block';
        elementsListView.appendChild(recordList);
        elementView.settingsArea.appendChild(elementsListView);
        const tableElements = dragElements.elementsValue;
        tableElements.forEach(tableElement =>{
          recordList.appendChild(tableElement.elementView);
        });
        // init autoCompleteValues for query
        const autoCompleteValues = [];
        dragElements.elementsValue.forEach(element =>{
          if (element.isNeedBindPoint && !(element.isCustomElement)) {
            autoCompleteValues.push({label: element.tableAttribute.labelName, value: element.tableAttribute.code});
            dragElements.query.queryMap[element.tableAttribute.labelName] = element.tableAttribute.code;
          }
        });
        // add query element
        const queryElement = ElementUtils.generateaQueryElementView();
        queryElement.id = `query_${appElementInfo.value.appId}`;
        elementView.query_elements_area.appendChild(ElementUtils
          .generateTextField(`${dragElements.elements[`${dragElements.appId}`].tableAttribute.labelName}`));
        elementView.query_elements_area.appendChild(queryElement);
        dragElements.query.queryElementId = queryElement.id;
        bindAutocompleteValues(queryElement.id, autoCompleteValues);
        bindFocusChangedListener(queryElement);
        dragElements.bindDoubleClick((element) =>{
          // show dataFormat dialog todo
        });
        return false;
      });
      // bind check box listener
      if (correctAppElementInfoLength === 1) {
        dragElementsList[0].bindCheckBoxButtonChange((target) =>{
          const elementId = `contact_${target.id}`;
          if (target.checked) {
            checkIsNeedShowGraphButton();
            const targetId = (target.id).slice(9);
            settingConfigInfo.contactConfigs[elementId] = new ContactConfigInfo([targetId]);
            const labelName = getCheckedText(targetId);
            const contactElement = initContactElement(elementId
              , new TableAttribute(labelName));
            elementView.contact_element_list.appendChild(contactElement.elementView);
            contactElement.dataSource.sourceId = targetId;
            contactElement.isCustomElement = originalData[targetId].isCustomElement;
            contactElements.addElement(contactElement);
          } else {
            deleteFromContactDataList(elementId);
          }
        });
      }
      // init Jsplumb point && bind Jsplumb event
      if (correctAppElementInfoLength > 1) {
        initJsPlumbEvent();
        bindJsplumbPoint();
      }
      // add contact_result_element_list
      elementView.contact_element_list.innerText = '';
      ElementUtils.addResultFieldTitle(i18n.mapping_result, elementView.contact_element_list);
      elementView.settingsArea.appendChild(elementView.contact_element_list);
      loadSettingConfigInfo();
    }).catch(error =>{
      window.alert(error.message);
    });
    return event;
  });
  const getCheckedText = (targetId)=> {
    return (isCustomElement(targetId))
      ? CommonUtils.removeSpecialSimbol(document.getElementById(targetId).children[0].children[0].value)
      : CommonUtils.removeSpecialSimbol(document.getElementById(targetId).children[0].innerText);
  };
  const loadSettingConfigInfo = ()=> {
    if (settingConfigInfo === undefined) {
      return;
    }
    // init custom element info
    const customLabelInfo = settingConfigInfo.customLabelInfo;
    Object.keys(customLabelInfo).forEach(customElementId =>{
      const labelName = customLabelInfo[customElementId];
      if (labelName !== '' && labelName !== undefined) {
        document.getElementById(customElementId).children[0].children[0].value = labelName;
      }
    });

    const contactConfigs = settingConfigInfo.contactConfigs;
    if (contactConfigs === undefined || Object.keys(contactConfigs).length === 0) {
      return;
    }
    const elementIds = Object.keys(contactConfigs);
    elementIds.forEach(elementId =>{
      const contactIds = contactConfigs[elementId].contactList;
      if (contactIds !== undefined) {
        if (contactIds.length > 1) {
          const sourceId = contactIds[0];
          const targetId = contactIds[1];
          jsPlumb.connect({
            uuids: [`uuid_${sourceId}_${Constant.ANCHORS_SITE_RIGHT}`, `uuid_${targetId}_${Constant.ANCHORS_SITE_LEFT}`]
          });
        } else {
          const checkedId = `checkbox_${contactIds[0]}`;
          document.getElementById(checkedId).checked = true;
          checkIsNeedShowGraphButton();
          let labelName = getCheckedText(contactIds[0]);
          const contactElement = initContactElement(elementId, new TableAttribute(labelName));
          labelName = contactConfigs[elementId].contactLabelName;
          elementView.contact_element_list.appendChild(contactElement.elementView);
          contactElement.dataSource.sourceId = contactIds[0];
          contactElements.addElement(contactElement);
          if (labelName !== undefined && labelName !== '') {
            document.getElementById(elementId).children[0].children[0].value = labelName;
            contactElements.elements[elementId].tableAttribute.labelName = labelName;
          }
        }
      }
    });
    const queryDatas = settingConfigInfo.queryDatas;
    if (queryDatas === undefined || queryDatas === null) {
      return;
    }
    queryDatas.forEach(queryData =>{
      (document.getElementById(queryData.queryElementId)).value = queryData.queryString;
    });
    showGraph();
  };
  const isCustomElement = (elementId)=> {
    if (originalData.hasOwnProperty(elementId)) {
      return originalData[elementId].isCustomElement;
    }
    return false;
  };
  const bindJsplumbPoint = ()=> {
    if (dragElementsList.length > 1) {
      dragElementsList.forEach((dragElements, index) =>{
        switch (index) {
          case 0:
            dragElements.bindPoint(Constant.ANCHORS_SITE_RIGHT);
            break;
          case dragElementsList.length - 1:
            dragElements.bindPoint(Constant.ANCHORS_SITE_LEFT);
            break;
          default:
            dragElements.bindPoint(Constant.ANCHORS_SITE_BOTH);
        }
      });
    }
  };
  const connectPoint = (sourceId, targetId) => {
    const elementId = CommonUtils.generateContactId(sourceId, targetId);
    // delete repeat line
    if (contactElements.elements.hasOwnProperty(elementId)) {
      return;
    }
    const contactKeys = Object.keys(contactElements.elements);
    contactKeys.forEach(contactKey =>{
      const originalIds = contactKey.split('|');
      if (sourceId === originalIds[0] || targetId === originalIds[1]) {
        deleteFromContactDataList(contactKey);
        checkIsNeedShowGraphButton();
      }
    });
    const contactElement = initContactElement(elementId, new TableAttribute(CommonUtils.generateContactText(sourceId, targetId)));
    contactElement.dataSource.sourceId = sourceId;
    contactElement.dataSource.targetId = targetId;
    contactElement.isCustomElement = originalData[sourceId].isCustomElement || originalData[targetId].isCustomElement;
    elementView.contact_element_list.appendChild(contactElement.elementView);
    contactElements.addElement(contactElement);

    // if configConfigs[elementId] has value set it into contactELement labelName
    const contactConfigs = settingConfigInfo.contactConfigs;
    if (contactConfigs !== undefined && contactConfigs[elementId] !== undefined && contactConfigs[elementId].contactLabelName !== undefined
      && contactConfigs[elementId].contactLabelName !== '') {
      const labelName = contactConfigs[elementId].contactLabelName;
      contactElements.elements[elementId].tableAttribute.labelName = labelName;
      document.getElementById(elementId).children[0].children[0].value = labelName;
    } else {
      settingConfigInfo.contactConfigs[elementId] = new ContactConfigInfo([sourceId, targetId]);
    }
  };
  const initJsPlumbEvent = ()=> {
    jsPlumb.bind('connection', (info) => {
      checkIsNeedShowGraphButton();
      connectPoint(info.sourceId, info.targetId);
    });
    jsPlumb.bind('connectionDetached', (info) => {
      deleteFromContactDataList(CommonUtils.generateContactId(info.sourceId, info.targetId));
    });
    jsPlumb.bind('dblclick', (conn) =>{
      deleteFromContactDataList(CommonUtils.generateContactId(conn.sourceId, conn.targetId));
      jsPlumb.deleteConnection(conn);
    });
  };
  const deleteFromContactDataList = (elementId)=> {
    delete (contactElements.elements)[elementId];
    // delete element in configInfo[contactConfigs]
    if (settingConfigInfo.contactConfigs !== undefined && settingConfigInfo.contactConfigs[elementId] !== undefined) {
      delete (settingConfigInfo.contactConfigs)[elementId];
    }
    if (!document.getElementById(elementId)) {
      return;
    }
    const element = document.getElementById(elementId);
    elementView.contact_element_list.removeChild(element);
    const bt_container = document.getElementById(Constant.SHOW_GRAPH_BT_ID);
    if (contactElements.elementsValue.length === 0 && bt_container) {
      elementView.settingsArea.removeChild(bt_container);
    }
  };
  const checkIsNeedShowGraphButton = ()=> {
    if (contactElements.elementsValue.length === 0) {
      const showTable = ElementUtils.generateShowGraphButton(i18n.show_graph);
      showTable.addEventListener('click', showGraph);
      elementView.settingsArea.appendChild(showTable);
    }
  };
  const initContactElement = (elementId, tableAttribute)=> {
    const contactElement = ElementUtils.generateInputElement(elementId
      , tableAttribute);
    contactElement.elementView.children[0].children[0].onblur = () =>{
      let contactLabel = document.getElementById(elementId).children[0].children[0].value;
      if (contactLabel === '') {
        if (contactElements.elements[elementId].isCustomElement) {
          contactLabel = getCurrentContactText(elementId);
        } else {
          contactLabel = contactElements.elements[elementId].originLabelName;
        }
        document.getElementById(elementId).children[0].children[0].value = contactLabel;
      }
      contactElements.elements[elementId].tableAttribute.labelName = contactLabel;
      settingConfigInfo.contactConfigs[elementId].contactLabelName = contactLabel;
    };
    return contactElement;
  };
  const initCustomElement = (appId, labelName)=> {
    const customElementId = `${appId}_${customizationIndex}`;
    const customElement = ElementUtils.generateInputElement(customElementId, new TableAttribute(labelName, `custom_${customizationIndex}`));
    customElement.isCustomElement = true;
    customElement.elementView.children[0].style.background = '#eeeeee';
    customElement.elementView.children[0].style.border = '1px solid gray';
    customizationIndex++;
    customElement.elementView.children[0].children[0].onblur = () =>{
      let customLabel = document.getElementById(customElementId).children[0].children[0].value;
      if (customLabel === '') {
        customLabel = originalData[customElementId].originLabelName;
        document.getElementById(customElementId).children[0].children[0].value = customLabel;
      }
      settingConfigInfo.customLabelInfo[customElementId] = customLabel;
    };
    return customElement;
  };
  const getCurrentContactText = (elementId)=> {
    const originalIds = elementId.split('|');
    if (originalIds.length > 1) {
      return CommonUtils.generateContactText(originalIds[0], originalIds[1]);
    } else if (originalIds.length === 1 && originalIds[0].length > 17) {
      return getCheckedText(originalIds[0].slice(17));
    }
    return contactElements.elements[elementId].originLabelName;

  };
  const checkPluginConfig = ()=>{
    return !pluginConfig.hasOwnProperty(Constant.CONFIG_FIRST_APP_ID) || !pluginConfig.hasOwnProperty(Constant.CONFIG_SECOND_APP_ID) ||
    !pluginConfig.hasOwnProperty(Constant.CONFIG_CONFIG_INFO_ID) || !pluginConfig.hasOwnProperty(Constant.CONFIG_SPACE_ID) ||
    `${pluginConfig[`${Constant.CONFIG_FIRST_APP_ID}`]}` === '' || `${pluginConfig[`${Constant.CONFIG_SECOND_APP_ID}`]}` === '' ||
    `${pluginConfig[`${Constant.CONFIG_CONFIG_INFO_ID}`]}` === '' || `${pluginConfig[`${Constant.CONFIG_SPACE_ID}`]}` === '';
  };
  const checkPermission = (record)=> {
    return (`${pluginConfig[`${Constant.CONFIG_FIRST_APP_ID}`]}` !== ''
    && !record.hasOwnProperty(`${pluginConfig[`${Constant.CONFIG_FIRST_APP_ID}`]}`))
    || `${pluginConfig[`${Constant.CONFIG_SECOND_APP_ID}`]}` !== ''
    && !record.hasOwnProperty(`${pluginConfig[`${Constant.CONFIG_SECOND_APP_ID}`]}`)
    || `${pluginConfig[`${Constant.CONFIG_CONFIG_INFO_ID}`]}` !== ''
    && !record.hasOwnProperty(`${pluginConfig[`${Constant.CONFIG_CONFIG_INFO_ID}`]}`);
  };
  const showGraph = ()=> {
    const getAppDatasRequests = [];
    viewManager.showLoading();
    dragElementsList.forEach(dragElements =>{
      const queryString = dragElements.query.getTrueQueryString();
      getAppDatasRequests.push(AppHttpRequestUtils.getAppDatas(dragElements.appId, queryString));
    });
    Promise.all(getAppDatasRequests).then(appDatas =>{
      originalData = {};
      appDatas.forEach((recordsData, index) =>{
        const dragElements = dragElementsList[index];
        dragElements.clearElementDataList();
        dragElements.putAppRecordDatasIntoElements(recordsData);
        originalData = Object.assign(originalData, dragElements.elements);
      });
      contactElements.elementsValue.forEach(element =>{
        if (element.dataSource.targetId === '') {
          element.elementDataList = originalData[element.dataSource.sourceId].elementDataList;
        } else {
          element.elementDataList = [...(originalData[element.dataSource.sourceId].elementDataList),
            ...(originalData[element.dataSource.targetId]).elementDataList];
        }
      });
      const analyzeData = CommonUtils.generateAnalyzeData(contactElements.elementsValue);
      let properties = {};
      if (settingConfigInfo.pivotConfig !== undefined && Object.keys(settingConfigInfo.pivotConfig).length > 0) {
        properties = settingConfigInfo.pivotConfig;
      } else if (analyzeData[0].length > 0) {
        properties.rows = [analyzeData[0][0]];
        properties.cols = [analyzeData[0][1]];
        properties.rendererName = 'Bar Chart';
      }
      properties.onRefresh = (pivotProperties)=> {
        const pivotConfig = JSON.parse(JSON.stringify(pivotProperties));
        // delete some values which are functions
        delete pivotConfig['aggregators'];
        delete pivotConfig['renderers'];
        // delete some bulky default values
        delete pivotConfig['rendererOptions'];
        delete pivotConfig['localeStrings'];
        settingConfigInfo.pivotConfig = pivotConfig;
      };
      properties.renderers = $.extend(
        $.pivotUtilities.renderers,
        $.pivotUtilities.plotly_renderers,
        $.pivotUtilities.export_renderers,
      );
      $('#graph_container').pivotUI(
        analyzeData, properties, false, lang
      );
      $('#tab_view').tabs({active: 1});
      viewManager.hideLoading();
    }).catch(error =>{
      viewManager.hideLoading();
      alert(error.message);
    });
  };
  const onSaveStatusButtonClick = ()=> {
    const queryDatas = [];
    dragElementsList.forEach(dragElements =>{
      queryDatas.push(dragElements.query);
    });
    settingConfigInfo.queryDatas = queryDatas;
    const configInfoString = JSON.stringify(settingConfigInfo);
    const record = {};
    record[`${pluginConfig[`${Constant.CONFIG_CONFIG_INFO_ID}`]}`] = {'value': configInfoString};
    AppHttpRequestUtils.updateAppRecord(kintone.app.getId(), kintone.app.record.getId(), record)
      .then((response) =>{
        alert('Save Success!');
      }).catch((error) =>{
        alert(error.message);
      });

  };
  // bind focus position changed event for textarea
  const bindFocusChangedListener = (element)=> {
    ['keyup', 'click', 'scroll'].forEach((event) =>{
      element.addEventListener(event, () =>{
        const coordinates = getCaretCoordinates(element, element.selectionEnd);
        focusPosition.left = coordinates.left;
        focusPosition.top = coordinates.top + coordinates.height;
        let height = element.style.height;
        height = height.substring(0, height.length - 2);
        if (focusPosition.top > parseInt(height, 10)) {
          focusPosition.top = height;
        }
      });
    });
  };
  const bindAutocompleteValues = (elementId, autoCompleteValues)=> {
    $(`#${elementId}`)
      .autocomplete({
        minLength: 0,
        position: {
          my: 'left top',
          at: 'left top',
          collision: 'none'
        },
        focus: ()=> {
          return false;
        },
        source: function(request, response) {
          // delegate back to autocomplete, but extract the last term
          if ((request.term).indexOf('#') !== -1) {
            const extract = extractLast(request.term);
            if (extract === '') {
              $(`#${elementId}`).autocomplete({
                position: {my: 'left top', at: `left+${focusPosition.left} top+${focusPosition.top}`, collision: 'none'}
              });
            }
            response($.ui.autocomplete.filter(
              autoCompleteValues, extract));
          }
        },
        select: function(e, ui) {
          var temp = this.value;
          var result = temp.substring(0, temp.lastIndexOf('#'));
          this.value = result + ui.item.label;
          return false;
        }
      });
    $(`#${elementId}`).data('ui-autocomplete')._resizeMenu = function() {
      this.menu.element.css({'width': 400});
    };
    function extractLast(term) {
      return term.split(/#\s*/).pop();
    }
  };
})(kintone.$PLUGIN_ID);